<template>
  <div>
    <div v-if="products.length === 0">空空如也</div>
    <ul>
      <li v-for="product in products">
        {{product.name}}: ￥{{product.price}} x {{product.quantity}}
      </li>
    </ul>
    <div>
      总价：￥{{totalPrice}}
    </div>
  </div>
</template>

<script>
export default {
  props: ['product'],

  data() {
    return {
      products: []
    }
  },

  computed: {
    totalPrice() {
      return this.products.reduce((total, product) => {
        total += product.price * product.quantity
        return total
      }, 0)
    }
  },

  watch: {
    product(p) {
      let product = this.products.find(value => value.id === p.id)
      if (!product) {
        this.products.push({
          id: p.id,
          name: p.name,
          price: p.price,
          quantity: 1
        })
      } else {
        product.quantity++
      }
    }
  }
}
</script>

<style lang='stylus' scoped>

</style>